package drds.plus.sql_process.utils;

import drds.plus.sql_process.abstract_syntax_tree.ObjectCreateFactory;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.Item;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.function.BooleanFilter;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.function.Filter;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.function.Operation;
import drds.plus.sql_process.abstract_syntax_tree.expression.item.function.OrsFilter;
import drds.plus.sql_process.parser.visitor.ExpressionVisitor;
import drds.tools.$;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class Filters {

    public static Object getFilterColumn(Filter filter) {
        if (filter instanceof BooleanFilter) {
            return ((BooleanFilter) filter).getColumn();
        } else if (filter instanceof OrsFilter) {
            return ((OrsFilter) filter).getColumn();
        } else {
            throw new UnsupportedOperationException("LogicFilter.getColumnMetaData");
        }

    }

    /**
     * 基于字符串表达式构建IFilter
     */
    public static Filter createFilter(String where) {
        if ($.isNullOrEmpty(where)) {
            return null;
        }
        ExpressionVisitor expressionVisitor = ExpressionVisitor.parser(where);
        Object value = expressionVisitor.getObject();
        if (value instanceof Filter) {
            return (Filter) value;
        } else if (value instanceof Item) {
            throw new IllegalArgumentException("illegal filter:" + where);
        } else {
            return expressionVisitor.buildConstantFilter(value);
        }
    }

    /**
     * 创建equal filter
     */
    public static BooleanFilter equal(Object columnName, Object value) {
        BooleanFilter booleanFilter = ObjectCreateFactory.createBooleanFilter();
        booleanFilter.setOperation(Operation.equal);
        booleanFilter.setColumn(columnName);
        booleanFilter.setValue(value);
        return booleanFilter;
    }

    /**
     * 根据column进行filter归类
     */
    public static Map<Object, List<Filter>> toColumnToFilterListMap(List<Filter> dnfFilterList) {
        Map<Object, List<Filter>> columnToFilterListMap = new HashMap(dnfFilterList.size());
        for (Filter dnfFilter : dnfFilterList) {
            Object column = null;
            if (dnfFilter instanceof BooleanFilter) {
                column = ((BooleanFilter) dnfFilter).getColumn();
            } else if (dnfFilter instanceof OrsFilter) {
                column = ((OrsFilter) dnfFilter).getColumn();
            }
            if (!columnToFilterListMap.containsKey(column)) {
                columnToFilterListMap.put(column, new LinkedList());
            }
            columnToFilterListMap.get(column).add(dnfFilter);
        }
        return columnToFilterListMap;
    }
}
